package api;

import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.Dish;
import model.ResultData;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@WebServlet("/orderdetail")
public class OrderDetailServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int state=-1;
        String msg="未知错误";
        List<Dish> data=new ArrayList<>();
        Integer oid=Integer.parseInt(req.getParameter("oid"));
        if(oid!=null&&oid>0){ // 参数有效
            Connection connection= DBUtil.getConnection();
            String sql="select * from dish where did in(select did from orderdetail where oid=?)";
            PreparedStatement statement=connection.prepareStatement(sql);
            statement.setInt(1,oid);
            ResultSet resultSet=statement.executeQuery();
            while(resultSet.next()){
                Dish dish=new Dish();
                dish.setName(resultSet.getString("name"));
                dish.setPrice(resultSet.getBigDecimal("price"));
                data.add(dish);
            }
            DBUtil.close(resultSet,statement,connection);
            state=200;
        }else{
            msg="参数无效";
        }
        // 将结果返回给前端
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(state,data,msg)));
    }
}
